import { defineStore } from 'pinia'
import { ref, shallowRef } from 'vue'

export const useDialogStore = defineStore('dialog', () => {
  // 存储所有活动的弹窗
  const dialogs = ref([])
  let nextId = 0

  // 打开一个新弹窗
  function open(config) {
    const id = nextId++
    dialogs.value.push({
      id,
      component: shallowRef(config.component), // 使用 shallowRef 避免深层响应式
      props: config.props || {},
      title: config.title || '对话框',
      visible: true,
      // 为每个弹窗设置一个随机的初始位置，防止重叠
      top: `${Math.floor(Math.random() * 15) + 10}%`,
      left: `${Math.floor(Math.random() * 15) + 25}%`,
    })
  }

  // 根据 ID 关闭弹窗
  function close(id) {
    const index = dialogs.value.findIndex(d => d.id === id)
    if (index > -1) {
      // 先设置 visible 为 false，然后移除
      dialogs.value[index].visible = false
      // 延迟移除，让动画完成
      setTimeout(() => {
        const currentIndex = dialogs.value.findIndex(d => d.id === id)
        if (currentIndex > -1) {
          dialogs.value.splice(currentIndex, 1)
        }
      }, 300)
    }
  }

  return { dialogs, open, close }
})
